/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import AccesoADatos.GlobalException;
import AccesoADatos.NoDataException;
import Logica.DatosConexion;
import Logica.Estrategia;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Fernando
 */
public class Strategy extends javax.swing.JPanel {

    /**
     * Creates new form Strategy
     */
    public Strategy(String n, DatosConexion dc, Principal p) {
        initComponents();
        this.prin = p;
        this.strategyName = n;
        this.datosCon = dc;
        strategyEsp.setText(strategyName);
        strategyEsp.setEditable(false);
        cargarTabla();
        //this.tablaS.is
        this.tablaS.getTableHeader().setReorderingAllowed(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        strategyEsp = new javax.swing.JTextField();
        viewBoton = new javax.swing.JButton();
        newBoton = new javax.swing.JButton();
        logBoton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaS = new javax.swing.JTable();
        chst = new javax.swing.JButton();

        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Server:");
        add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(34, 57, -1, -1));
        add(strategyEsp, new org.netbeans.lib.awtextra.AbsoluteConstraints(88, 54, 101, -1));

        viewBoton.setText("VIEW");
        viewBoton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewBotonActionPerformed(evt);
            }
        });
        add(viewBoton, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 440, -1, -1));

        newBoton.setText("NEW");
        newBoton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newBotonActionPerformed(evt);
            }
        });
        add(newBoton, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 440, -1, -1));

        logBoton.setText("LOG");
        add(logBoton, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 440, -1, -1));

        tablaS = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false; //Disallow the editing of any cell
            }
        };
        tablaS.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STRATEGY", "TYPE", "RMAN", "STATUS", "TIME"
            }
        ));
        tablaS.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaSMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaS);

        add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 220, 692, 150));

        chst.setText("STATUS");
        chst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chstActionPerformed(evt);
            }
        });
        add(chst, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 440, -1, -1));
    }// </editor-fold>//GEN-END:initComponents

    private void newBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newBotonActionPerformed
        CreateStrategy cst;
        try {
            cst = new CreateStrategy(getDatosCon(), this.prin, this.strategyName, this);
            cst.setVisible(true);
        } catch (GlobalException ex) {
            Logger.getLogger(Strategy.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoDataException ex) {
            Logger.getLogger(Strategy.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_newBotonActionPerformed

    private void tablaSMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaSMouseClicked
        
    }//GEN-LAST:event_tablaSMouseClicked

    private void viewBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewBotonActionPerformed
        int r = tablaS.getSelectedRow();
        if (r == -1) {
            JOptionPane.showMessageDialog(null, "There is not strategy selected.");
        } else {
            String rm = (String) tablaS.getValueAt(r, 2);
            String horario = (String) tablaS.getValueAt(r, 4);
            Leer reading = new Leer(this.leeRman(rm), rm, horario);
            reading.setVisible(true);
        }
        //JOptionPane.showMessageDialog(null, r);
    }//GEN-LAST:event_viewBotonActionPerformed

    private void chstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chstActionPerformed
        int r = tablaS.getSelectedRow();

        if (r == -1) {
            JOptionPane.showMessageDialog(null, "There is not strategy selected.");
        } else {
            String chs = (String) tablaS.getValueAt(r, 0);
            Object[] options = {"Yes", "No"};
            int op = JOptionPane.showOptionDialog(this, "Do you want to change the status of " + chs + "?", "Change Status", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (op == 0) {
                Estrategia str = this.prin.buscaEstrategia(chs);
                str.setStatus(!(str.isStatus()));
                cargarTabla();
                try {
                    this.prin.actualizarArchivo();
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Strategy.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Strategy.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                JOptionPane.showMessageDialog(null, "The status has not been changed.");
            }
        }

    }//GEN-LAST:event_chstActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton chst;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton logBoton;
    private javax.swing.JButton newBoton;
    private javax.swing.JTextField strategyEsp;
    private javax.swing.JTable tablaS;
    private javax.swing.JButton viewBoton;
    // End of variables declaration//GEN-END:variables
    private String strategyName;
    private DatosConexion datosCon;
    private Principal prin;

    public String getStrategyName() {
        return strategyName;
    }

    public void setStrategyName(String strategyName) {
        this.strategyName = strategyName;
    }

    public DatosConexion getDatosCon() {
        return datosCon;
    }

    public void setDatosCon(DatosConexion datosCon) {
        this.datosCon = datosCon;
    }

    public Principal getPrin() {
        return prin;
    }

    public void setPrin(Principal prin) {
        this.prin = prin;
    }

    public void cargarTabla() {

        for (int i = 0; i < ((DefaultTableModel) tablaS.getModel()).getRowCount();) {
            ((DefaultTableModel) tablaS.getModel()).removeRow(i);
        }

        //agrega lo que haya en el arraylist
        for (int i = 0; i < this.prin.Estrategias(strategyName).size(); i++) {
            Estrategia ser = this.prin.Estrategias(strategyName).get(i);
            String type = "INCREMENTAL";
            String stat = "INACTIVE";

            if (ser.isTipo()) {
                type = "FULL";
            }

            if (ser.isStatus()) {
                stat = "ACTIVE";
            }

            String[] datos = {ser.getNombre(), type, ser.getRman(), stat, ser.getHorario()};
            ((DefaultTableModel) tablaS.getModel()).addRow(datos);
            ((DefaultTableModel) tablaS.getModel()).isCellEditable(i, 0);
        }
    }

    public String leeRman(String rm) {

        String todo = "";
        try {
            // Abrimos el archivo
            FileInputStream fstream = new FileInputStream(rm);
            // Creamos el objeto de entrada
            DataInputStream entrada = new DataInputStream(fstream);
            // Creamos el Buffer de Lectura
            BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
            String strLinea;
            // Leer el archivo linea por linea
            while ((strLinea = buffer.readLine()) != null) {
                // Imprimimos la línea por pantalla
                //System.out.println(strLinea);
                todo = todo + strLinea + "\n";

            }
            // Cerramos el archivo
            entrada.close();

            return todo;
        } catch (Exception e) { //Catch de excepciones
            JOptionPane.showMessageDialog(this, "error leyendo archivo");
            return null;
        }
    }
}
